package com.aerozhonghuan.logisticsmall.modules.order;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.framework.base.TitlebarFragment;
import com.aerozhonghuan.logisticsmall.modules.mine.adapter.OrderInfoPlistAdapter;
import com.aerozhonghuan.logisticsmall.modules.order.base.OrderState;
import com.aerozhonghuan.logisticsmall.modules.order.beans.OrderDetailBean;
import com.aerozhonghuan.logisticsmall.modules.order.beans.OrdersListBean;
import com.aerozhonghuan.logisticsmall.modules.order.logic.OrderStateControl;
import com.aerozhonghuan.logisticsmall.modules.order.logic.OrderWebRequest;
import com.aerozhonghuan.logisticsmall.widget.CustomDialog;
import com.aerozhonghuan.logisticsmall.widget.ProgressDialogIndicator;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;
import com.blankj.utilcode.util.ActivityUtils;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 描述 订单详情页面
 *
 * @author Zhang Yonghui
 * 创建日期 2019-05-17
 */
public class OrderDetailFragment extends TitlebarFragment implements View.OnClickListener {

    private View rootView;
    private String billId;
    private ProgressDialogIndicator progressDialogIndicator;
    private ImageView imgStatus;
    private TextView tvDesc, tvNamePhone, tvCompany, tvStationname, tvTotalprice, tvActualprice, tvOrderinfo;
    private LinearLayout llCommoditys, llCall;
    private RelativeLayout relActualPrice, relMore;
    private OrderState orderState;
    private OrderDetailBean orderDetailBean;
    private Button btnMore;
    private LayoutInflater inflater;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_order_detail, null);
            billId = getArguments().getString("billId");
            if (TextUtils.isEmpty(billId)) {
                alert("数据异常");
                getActivity().finish();
            }
            initView();
            initData();
        }
        return rootView;
    }

    private void initView() {
        inflater = LayoutInflater.from(getContext());
        progressDialogIndicator = new ProgressDialogIndicator(getContext());
        imgStatus = (ImageView) rootView.findViewById(R.id.img_status);
        tvDesc = (TextView) rootView.findViewById(R.id.tv_desc);
        tvNamePhone = (TextView) rootView.findViewById(R.id.tv_name_phone);
        tvCompany = (TextView) rootView.findViewById(R.id.tv_company);
        tvStationname = (TextView) rootView.findViewById(R.id.tv_stationname);
        tvTotalprice = (TextView) rootView.findViewById(R.id.tv_totalprice);
        llCommoditys = (LinearLayout) rootView.findViewById(R.id.ll_commoditys);
        tvOrderinfo = (TextView) rootView.findViewById(R.id.tv_orderinfo);
        llCall = (LinearLayout) rootView.findViewById(R.id.ll_call);
        relActualPrice = (RelativeLayout) rootView.findViewById(R.id.rel_actualPrice);
        tvActualprice = (TextView) rootView.findViewById(R.id.tv_actualPrice);
        relMore = (RelativeLayout) rootView.findViewById(R.id.rel_more);
        rootView.findViewById(R.id.rel_userinfo).setOnClickListener(this);
        rootView.findViewById(R.id.btn_callstore).setOnClickListener(this);
        rootView.findViewById(R.id.btn_callcompany).setOnClickListener(this);
        btnMore = (Button) rootView.findViewById(R.id.btn_more);
        btnMore.setOnClickListener(this);
    }

    private void initData() {
        OrderWebRequest.queryOrderDetail(getContext(), progressDialogIndicator, billId, new CommonCallback<OrderDetailBean>() {
            @Override
            public void onSuccess(OrderDetailBean bean, CommonMessage commonMessage, String allResponseString) {
                if (getActivity() == null && getActivity().isFinishing()) {
                    return;
                }
                orderDetailBean = bean;
                orderState = OrderStateControl.getOrderStateByCode(orderDetailBean.getBillStatus());
                if (orderState != null) {
                    fillingView();
                }
            }
        });
    }

    private void fillingView() {
        imgStatus.setImageResource(orderState.infoIconId);
        tvDesc.setText(orderState.infoDesc);
        if (orderDetailBean.getCustomer() != null) {
            tvNamePhone.setText(String.format("%s    %s", orderDetailBean.getCustomer().getName(), orderDetailBean.getCustomer().getPhone()));
        }
        if (orderDetailBean.getStation() != null) {
            tvStationname.setText(orderDetailBean.getStation().getName());
            tvCompany.setText(orderDetailBean.getCompany().getName());
        }
        tvTotalprice.setText(String.format("¥ %s", (float) orderDetailBean.getTotalPrice() / 100));
        if (orderState.isHaveactualPrice) {
            relActualPrice.setVisibility(View.VISIBLE);
            tvActualprice.setText(String.format("¥ %s", (float) orderDetailBean.getActualPrice() / 100));
        } else {
            relActualPrice.setVisibility(View.GONE);
        }
        if (orderDetailBean.getCompany() != null && !TextUtils.isEmpty(orderDetailBean.getCompany().getPhone()) && orderDetailBean.getStation() != null && !TextUtils.isEmpty(orderDetailBean.getStation().getPhone())) {
            llCall.setVisibility(View.VISIBLE);
        }
        if (orderState.isHaveActionBtn) {
            relMore.setVisibility(View.VISIBLE);
            btnMore.setText(orderState.actionBtnText);
        } else {
            relMore.setVisibility(View.GONE);
            btnMore.setText("");
        }
        LinkedHashMap<String, String> infoMap = orderState.initStateInfoItemMap(orderDetailBean);
        StringBuffer content = new StringBuffer();
        int i = 0;
        for (String title: infoMap.keySet()) {
            i++;
            content.append(String.format("%s：&nbsp&nbsp%s", title, String.format("<b>%s</>", infoMap.get(title))));
            if (i != infoMap.size()) {
                content.append("<br />");
            }
        }
        tvOrderinfo.setText(Html.fromHtml(content.toString()));
        fillingPlist();
    }

    // 填充商品列表
    private void fillingPlist() {
        List<OrdersListBean.CommodityListBean> plist = orderDetailBean.getPlist();
        OrderInfoPlistAdapter adapter = new OrderInfoPlistAdapter(plist, getContext());
        for (int i = 0; i < plist.size(); i++) {
            View convertView = null;
            convertView = adapter.getView(i, convertView, null);
            llCommoditys.addView(convertView);
            View line = inflater.inflate(R.layout.split_line_left15, null);
            if (plist.size() > 1 && i < plist.size() - 1) {
                llCommoditys.addView(line);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rel_userinfo:
                double lat = orderDetailBean.getStation().getLat();
                double lon = orderDetailBean.getStation().getLng();
                Intent intent = new Intent(getContext(), StationLocationAcrivity.class).putExtra("lon", lon).putExtra("lat", lat);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.btn_callstore:
                call(orderDetailBean.getStation().getPhone());
                break;
            case R.id.btn_callcompany:
                call(orderDetailBean.getCompany().getPhone());
                break;
            case R.id.btn_more:
                orderState.getDialog(getContext(), String.valueOf(orderDetailBean.getBillId()), new OrderState.OnDialogListener() {
                    @Override
                    public void onSuccess() {
                        initData();
                    }

                    @Override
                    public void onFailure() {

                    }
                }).showDialog();
                break;
            default:
                break;
        }
    }

    private void call(final String phone) {
        if (!TextUtils.isEmpty(phone) && !TextUtils.equals(phone, "null")) {
            new CustomDialog(getActivity(), "", String.format("确定拨打电话\n%s", phone), "确定", "取消").setOnDiaLogListener(new CustomDialog.OnDialogListener() {
                @Override
                public void dialogPositiveListener() {
                    Intent tel_intent = new Intent(Intent.ACTION_CALL, Uri.parse(String.format("tel:%S", phone)));
                    startActivity(tel_intent);
                }

                @Override
                public void dialogNegativeListener() {
                }
            }).showDialog();
        } else {
            alert("暂无电话");
        }
    }
}
